package com.erbadagang.springboot.rsa.util;

import lombok.Getter;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

/**
 * @description RSA公私钥对生成工具, 加解密处理注意：密钥长度2048
 * @ClassName: RsaGenerator
 * @author: 郭秀志 jbcode@126.com
 * @date: 2020/7/25 11:16
 * @Copyright:
 */
@Getter
public class RsaGenerator {

    /**
     * 加密算法RSA
     */
    public static final String KEY_ALGORITHM = "RSA";

    /**
     * 获取公钥的key
     */
    private RSAPublicKey publicKey;

    /**
     * 获取私钥的key
     */
    private RSAPrivateKey privateKey;

    /**
     * <p>
     * 生成密钥对(公钥和私钥)
     * </p>
     *
     * @return
     * @throws Exception
     */
    public void generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(2048);
        KeyPair keyPair = keyPairGen.generateKeyPair();

        this.publicKey = (RSAPublicKey) keyPair.getPublic();
        this.privateKey = (RSAPrivateKey) keyPair.getPrivate();
    }

}
